<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
<div id="app">
  <div v-if="books.length">
    <table>
      <thead>
      <tr>
        <th></th>
        <th>书籍名称</th>
        <th>出版日期</th>
        <th>价格</th>
        <th>购买数量</th>
        <th>操作</th>
      </tr>
      </thead>
      <tbody>
      <tr v-for="(item , index) in books">
        <td>{{item.id}}</td>
        <td>{{item.name}}</td>
        <td>{{item.date}}</td>
        <td>{{item.price | showPrice}}</td>
        <td>
          <button @click="increment(index)">+</button>
          {{index}}
          {{item.count}}
          <button @click="decrement(index)" :disabled="item.count <=1">-</button>
        </td>
        <td>
          <button @click="removeHandler(index)">移除</button>
        </td>
      </tr>
      </tbody>
    </table>
    <h2>总价格:{{totalPrice | showPrice}}</h2>
  </div>
  <div v-else>
    <h2>购物车为空</h2>
  </div>

</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script>
<script>
  const app = new Vue({
    el: '#app',
    data: {
      books:
          [
            {id: 1, name: '相对论', date: '2006-8', price: 111.00, count: 1},
            {id: 2, name: '时间简史', date: '2006-8', price: 22.00, count: 1},
            {id: 3, name: '算法', date: '2006-8', price: 33.00, count: 1},
            {id: 4, name: '离散数学', date: '2006-8', price: 42.00, count: 1}
          ]
    },
    methods: {
      increment(index) {
        this.books[index].count++
      },
      decrement(index) {
        this.books[index].count--
      },
      removeHandler(index) {
        this.books.splice(index, 1)
      }
    },
    computed: {
      totalPrice() {
        //1.普通for循环
        // let totalPrice = 0;
        // for (let i = 0; i < this.books.length; i++) {
        //   totalPrice += this.books[i].price * this.books[i].count
        // }
        // return totalPrice

        for(let items of this.books){
          console.log(items.id);
        }
      }
    },
    filters: {
      showPrice(price) {
        return '￥' + price.toFixed(2)
      }
    }
  })
</script>
</body>
</html>
